package com.team9.fitness.controller;

import com.team9.fitness.entity.PostComment;
import com.team9.fitness.service.PostCommentService;
import com.team9.fitness.service.ZRDDSDataExchangeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 帖子评论控制器
 * 
 * 提供帖子评论相关的REST API：
 * - 评论管理：创建、更新、删除评论
 * - 查询功能：支持按帖子、用户、ID查询，支持排序
 * - 统计功能：统计评论的点赞数量
 * - 状态管理：支持用户点赞状态查询
 */
@RestController
@RequestMapping("/api/post-comments")
@CrossOrigin(origins = { "*" }, allowCredentials = "false")
@Slf4j
public class PostCommentController {

    @Autowired
    private PostCommentService postCommentService;

    @Autowired
    private ZRDDSDataExchangeService zrddsDataExchangeService;

    /**
     * 创建评论
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createComment(@RequestBody PostComment comment) {
        Map<String, Object> response = new HashMap<>();

        try {
            log.info("收到创建评论请求: userId={}, postId={}", comment.getUserId(), comment.getPostId());

            // 直接执行业务逻辑
            PostComment createdComment = postCommentService.createComment(comment);
            response.put("success", true);
            response.put("message", "评论创建成功");
            response.put("data", createdComment);

            // 业务逻辑成功，发布数据到ZRDDS作为记录
            try {
                Map<String, Object> additionalData = new HashMap<>();
                additionalData.put("postId", comment.getPostId());
                additionalData.put("content", comment.getContent());
                additionalData.put("createTime", java.time.LocalDateTime.now().toString());

                zrddsDataExchangeService.publishCommunityActivity("ADD_COMMENT",
                        comment.getUserId(), comment.getPostId(), additionalData);
            } catch (Exception e) {
                log.warn("发布社区活动数据到ZRDDS失败", e);
                // 不影响业务逻辑
            }

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("创建评论失败", e);
            response.put("success", false);
            response.put("message", "创建失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 根据帖子ID获取评论列表（包含统计信息）
     */
    @GetMapping("/post/{postId}")
    public ResponseEntity<Map<String, Object>> getCommentsByPostId(@PathVariable Long postId,
            @RequestParam(required = false) Long currentUserId) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 如果未提供currentUserId，使用0表示未登录用户
            Long currentUser = currentUserId != null ? currentUserId : 0L;
            List<PostComment> comments = postCommentService.getCommentsByPostId(postId, currentUser);
            response.put("success", true);
            response.put("data", comments);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取评论列表失败", e);
            response.put("success", false);
            response.put("message", "获取失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 根据用户ID获取评论列表（包含统计信息）
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getCommentsByUserId(@PathVariable Long userId,
            @RequestParam(required = false) Long currentUserId) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 如果未提供currentUserId，使用0表示未登录用户
            Long currentUser = currentUserId != null ? currentUserId : 0L;
            List<PostComment> comments = postCommentService.getCommentsByUserId(userId, currentUser);
            response.put("success", true);
            response.put("data", comments);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取用户评论失败", e);
            response.put("success", false);
            response.put("message", "获取失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 根据ID获取评论（包含统计信息）
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getCommentById(@PathVariable Long id,
            @RequestParam(required = false) Long currentUserId) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 如果未提供currentUserId，使用0表示未登录用户
            Long currentUser = currentUserId != null ? currentUserId : 0L;
            var comment = postCommentService.getCommentById(id, currentUser);
            if (comment.isPresent()) {
                response.put("success", true);
                response.put("data", comment.get());
            } else {
                response.put("success", false);
                response.put("message", "评论不存在");
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取评论失败", e);
            response.put("success", false);
            response.put("message", "获取失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 更新评论
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateComment(@PathVariable Long id, @RequestBody PostComment comment) {
        Map<String, Object> response = new HashMap<>();

        try {
            comment.setId(id);
            PostComment updatedComment = postCommentService.updateComment(comment);
            response.put("success", true);
            response.put("message", "评论更新成功");
            response.put("data", updatedComment);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("更新评论失败", e);
            response.put("success", false);
            response.put("message", "更新失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 删除评论
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteComment(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();

        try {
            postCommentService.deleteComment(id);
            response.put("success", true);
            response.put("message", "评论删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除评论失败", e);
            response.put("success", false);
            response.put("message", "删除失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
}
